const { bfmetaSDK } = require('../../../util/util')
const { signature } = require('../../../util/signature')

const trDestoryEntity = () => {
    return async (req, res, next) => {
        try {
            if(!req.body.transactionSignature || !req.body.entityId || !req.body.entityFactoryApplicant || !req.body.entityFactoryPossessor || !req.body.entityPrealnum || !req.body.entityFrozenAssetPrealnum || !req.body.purchaseAssetPrealnum || !req.body.recipientId || !req.body.publicKey || !req.body.secretKey){
                return res.status(400).send({
                    success: false,
                    message: "参数不能为空"
                })
            }
            let data = {
                transactionSignature: req.body.transactionSignature,
                entityId: req.body.entityId,
                entityFactoryApplicant: req.body.entityFactoryApplicant,
                entityFactoryPossessor: req.body.entityFactoryPossessor,
                entityPrealnum: req.body.entityPrealnum,
                entityFrozenAssetPrealnum: req.body.entityFrozenAssetPrealnum,
                purchaseAssetPrealnum: req.body.purchaseAssetPrealnum,
                recipientId: req.body.recipientId,
                publicKey: req.body.publicKey,
                fee: "2000",
                applyBlockHeight: 1
            }
            // 发起销毁权益资产事件
            let result = await bfmetaSDK.api.transaction.createDestroyEntity(data)
            if(!result.success){
                return res.status(400).send(result)
            }
            // 对该事件进行签名
            const _signature = await signature(result.result.buffer, req.body.secretKey)
            data = {
                signature: _signature,
                buffer: result.result.buffer
            }
            // 广播销毁权益资产事件
            result = await bfmetaSDK.api.transaction.broadcastDestroyEntity(data)
            if(!result.success){
                return res.status(400).send(result)
            }
            res.status(200).send(result)
        }
         catch (error) {
            next(error)
        }
    }
}

module.exports = { trDestoryEntity }